package profile

import (
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
	uuid "github.com/satori/go.uuid"
	"h8QuestionnaireServer/components/cache"
	"h8QuestionnaireServer/pojo/constant"
	"h8QuestionnaireServer/pojo/response"
	"h8QuestionnaireServer/service"
	"net/http"
	"strings"
)

// 微信小程序登陆
func AuthProfile(ctx *gin.Context) {
	param := struct {
		Code string `form:"code"`
	}{}
	err := ctx.ShouldBindQuery(&param)
	if err != nil {
		ctx.JSON(http.StatusOK, response.GenError(response.PARAM_ERROR, ""))
	} else {
		log.Info().Msgf("%s", param.Code)
	}

	user, err := service.Login(param.Code)
	if err != nil || user == nil {
		ctx.JSON(200, response.GenError(response.GENERAL_ERROR, "登录失败"))
		return
	} else {
		log.Info().Msgf("%s", "登陆成功")
	}

	token := strings.Replace(uuid.NewV1().String(), "-", "", -1)
	cache.GetConn(constant.SESSION_CACHE_DB).SetEx(token, 7200, user.Openid)
	cache.GetConn(constant.SESSION_CACHE_DB).SetEx(user.Openid, 7200, token)
	resp := response.GenSuccess(token)
	ctx.JSON(200, resp)
}